package emulator.hardware.clock;

public class ClockHandleImpl2 implements ClockHandle {

	private int ticks_avail = 0;
	private ClockImpl2 clock = null;
	private long ticks_elapsed = 0;
	
	ClockHandleImpl2(ClockImpl2 clock)
	{
		this.clock = clock;
	}
	
	synchronized public boolean grantTicks(int ticks_granted)
	{
		ticks_avail += ticks_granted;
		if (ticks_avail > 0)
		{	
			notify();
			return true;
		}
		else
			return false;
	}
	
	synchronized private void consumeTicks(int ticks_consumed)
	{
		ticks_avail -= ticks_consumed;
		ticks_elapsed += ticks_consumed;
	}
	
	synchronized private void waitTicksAvail()
	{
		while (ticks_avail <= 0)
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO
			}
	}
	
	synchronized private boolean areTicksAvailable()
	{
		return ticks_avail > 0;
	}
	
	@Override
	public void tick() {
		tick(1);
	}

	@Override
	public void tick(int ticks_consumed) {
		consumeTicks(ticks_consumed);
		if (!areTicksAvailable())
		clock.requestTicks(this);
		waitTicksAvail();
	}

	@Override
	public long getTicks() {
		return ticks_elapsed;
	}

	
}
